using PrimeTween;
using UnityEngine;

namespace Audio
{
    [RequireComponent(typeof(AudioSource))]
    public class AudioPlayer : MonoBehaviour
    {
        public static AudioPlayer Instance { get; private set; }

        private AudioSource _audioSource;

        private Tween _volumeTween;

        
        private void Awake()
        {
            if (Instance != null)
            {
                Destroy(gameObject);
                return;
            }
            
            Instance = this;
            _audioSource = GetComponent<AudioSource>();
            
            DontDestroyOnLoad(gameObject);
        }

        public void PlaySound(AudioClip audioClip) =>
            _audioSource.PlayOneShot(audioClip);

        public void PlayRandom(params AudioClip[] audioClips)
        {
            int index = Random.Range(0, audioClips.Length);
            PlaySound(audioClips[index]);
        }

        public void ToggleMute()
        {
            _audioSource.mute = !_audioSource.mute;
        }

        public void SetVolume(float volume)
        {
            _volumeTween.Stop();
            if (_audioSource == null)
            {
                return;
            }
            
            _volumeTween = Tween.AudioVolume(_audioSource, volume, 1f, useUnscaledTime: true);
        }
    }
}

